package com.pucong.gitee.database.backup.business.database.util;

import com.pucong.gitee.database.backup.common.entity.database.AutoDataSource;
import com.pucong.gitee.database.backup.common.selfenum.DatabaseDriverClassEnum;
import com.pucong.gitee.database.backup.configuration.exception.BusinessException;
import com.pucong.gitee.database.backup.business.database.mapper.AutoExeSqlLogMapper;
import org.apache.commons.lang3.StringUtils;

public class OperationServicePgsqlImpl extends AbstractOperationService {

    private static final String URL_PREFIX = "jdbc:postgresql://";

    private static final String URL_LAST = "useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true";

    public OperationServicePgsqlImpl(AutoDataSource autoDataSource, AutoExeSqlLogMapper autoExeSqlLogMapper) {
        super(autoDataSource, autoExeSqlLogMapper);
        if(StringUtils.isBlank(autoDataSource.getDatabaseName())){
            throw new BusinessException("数据库名称不能为空");
        }
    }

    @Override
    public void initUrl() {
        if(StringUtils.isBlank(autoDataSource.getSchemaName())){
            autoDataSource.setSchemaName("public");
        }
        this.url = URL_PREFIX  + autoDataSource.getHost() + ":" + autoDataSource.getPort() + "/" + autoDataSource.getDatabaseName() + "?currentSchema="+ autoDataSource.getSchemaName() +"&" + URL_LAST;
        this.driverClassName = DatabaseDriverClassEnum.postgresql.getClassName();
    }

    @Override
    public String generatePageSql(String sql, Integer pageNum, Integer pageSize) {
        if(StringUtils.isBlank(sql)){
            throw new BusinessException("sql语句为空");
        }
        if(pageNum == null){
            pageNum = 1;
        }
        if(pageSize == null){
            pageSize = 10;
        }

        String result = sql;

        int offset = (pageNum - 1) * pageSize;
        result = "select * from ("+sql+") t limit " + pageSize + " OFFSET " + offset;
        return result;
    }
}
